package middleware

import (
	"fmt"
	"gitee.com/xluomo945/fm/helper"
	"gitee.com/xluomo945/fm/jwt"
	"github.com/gin-gonic/gin"
)

func Auth(ctx *gin.Context) {
	token := jwt.GetJwtToken(ctx)
	if helper.StringEmpty(token) {
		ctx.AbortWithStatusJSON(jwt.GetUnAuthorizedHttpCode(), gin.H{
			"code": jwt.GetUnAuthorizedCode(),
			"msg":  jwt.GetUnAuthorizedMessage(fmt.Errorf("token is empty")),
		})
		return
	}

	v, e := jwt.ParseToken(token)
	if e != nil {
		ctx.AbortWithStatusJSON(jwt.GetUnAuthorizedHttpCode(), gin.H{
			"code": jwt.GetUnAuthorizedCode(),
			"msg":  jwt.GetUnAuthorizedMessage(e),
		})
		return
	}

	jwt.SetPayload(ctx, v)
}
